package com.carkeeper.caruser.service.impl;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.carkeeper.caruser.dao.UserMapper;
import com.carkeeper.caruser.easy.WriteModel;
import com.carkeeper.caruser.pojo.User;
import com.carkeeper.caruser.service.EsayService;

import com.carkeeper.caruser.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class EsayServiceImpl implements EsayService {

    @Autowired
    private UserMapper userMapper;

    @Value("${esaypath}")
    private String esaypath;

    /**
     * 生成车主信息表格
     */
    @Override
    public void createEsay(Integer currentpage,Integer pagesize) {
        try {
            //文件输出位置
            OutputStream outputStream = new FileOutputStream(esaypath+currentpage+".xlsx");

            ExcelWriter writer = EasyExcelFactory.getWriter(outputStream);

            Sheet sheet = new Sheet(0,1,WriteModel.class);
            //传递第一个sheet名称
            sheet.setSheetName("车主信息");

            writer.write(getWriteModels(currentpage,pagesize),sheet);
            writer.finish();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 填充信息到表格
     * @return
     */
    private List<WriteModel> getWriteModels(Integer currentpage,Integer pagesize) {
        PageHelper.startPage(currentpage, pagesize);
        List<User> users = userMapper.selectAll();
        PageInfo<User> userPageInfo = new PageInfo<>(users);
        List<User> list = userPageInfo.getList();
        List<WriteModel> writeModels = new ArrayList<>();
        for (User user : list) {
            WriteModel writeModel = new WriteModel();
            writeModel.setId(user.getId()+"");
            writeModel.setUsername(user.getUsername());
            writeModel.setPhone(user.getPhone());
            String status = user.getStatus().toString();
            if ("1".equals(status)) {
                status = "正常";
            }
            if ("0".equals(status)) {
                status = "锁定";
            }
            writeModel.setStatus(status);
            writeModels.add(writeModel);
        }
        return writeModels;

    }
}
